{% extends 'base.html' %}

{% block title %}
生成报价单 - 数据管理系统
{% endblock %}

{% block breadcrumb %}
<li class="breadcrumb-item"><a href="{{ url_for('list_main') }}">产品列表</a></li>
<li class="breadcrumb-item"><a href="{{ url_for('cart.cart') }}">购物车</a></li>
<li class="breadcrumb-item active" aria-current="page">生成报价单</li>
{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
  <h2 class="page-header">生成报价单</h2>
  <a href="{{ url_for('cart.cart') }}" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> 返回购物车</a>
</div>
<form id="quotationForm" class="mb-4">
  <div class="row g-3">
    <div class="col-md-3">
      <label for="salesperson" class="form-label">销售员</label>
      <select class="form-select" id="salesperson" name="salesperson">
        <option value="">加载中...</option>
      </select>
    </div>
    <div class="col-md-3">
      <label for="company" class="form-label">公司</label>
      <select class="form-select" id="company" name="company">
        <!-- 动态加载公司列表 -->
      </select>
    </div>
    <div class="col-md-3">
      <label for="quoteCurrency" class="form-label">报价货币</label>
      <select class="form-select" id="quoteCurrency" name="quote_currency">
        <option value="">加载中...</option>
      </select>
    </div>
    <div class="col-md-3">
      <label for="profitRate" class="form-label">利润率 (%)</label>
      <input type="number" step="0.01" class="form-control" id="profitRate" name="profit_rate" value="30">
    </div>
  </div>
</form>
<div class="mt-3">
  <strong>当前汇率：</strong>
  <span id="exchangeRateDisplay" class="text-muted">未加载</span>
</div>

{% if cart_items %}
<div class="table-responsive">
  <table class="table table-striped table-hover">
    <thead class="table-light">
      <tr>
        <th scope="col">图片</th>
        <th scope="col">型号</th>
        <th scope="col">描述</th>
        <th scope="col">英文描述</th>
        <th scope="col">公司</th>
        <th scope="col">进货价 (¥)</th>
        <th scope="col" id="priceHeader">Sales Price (USD)</th>
      </tr>
    </thead>
    <tbody>
      {% for item in cart_items %}
      <tr data-product-id="{{ item.product_id }}" data-product-detail-id="{{ item.product_detail_id }}">
        <td>
          {% if item.product_detail and item.product_detail.local_image_path %}
          <img src="{{ url_for('static', filename=item.product_detail.local_image_path) }}" style="width: 200px;">
          {% else %}
          <span class="text-muted">无图片</span>
          {% endif %}
        </td>
        <td>
          <a href="{{ url_for('list_details', product_id=item.product_id) }}"
            title="{{ item.product_detail.description }}" target="_blank"> {% if item.product_detail
            %}
            {{ item.product_detail.self_model or '默认规格' }}
            {% else %}
            <span class="text-muted">无规格</span>
            {% endif %}
          </a>
        </td>
        <td>
          {% if item.product_detail %}
          {{ item.product_detail.description or '无描述' }}
          {% else %}
          <span class="text-muted">无描述</span>
          {% endif %}
        </td>
        <td>
          {% if item.product_detail %}
          {{ item.product_detail.description_en or 'no description' }}
          {% else %}
          <span class="text-muted">无描述</span>
          {% endif %}
        </td>
        <td>{{ item.product.company_name }}</td>
        <td>
          {% if item.product_detail and item.product_detail.price %}
          <span class="badge bg-success data-cost-price">¥{{ '%.2f'|format(item.product_detail.price) }}</span>
          {% else %}
          <span class="text-muted">未设置</span>
          {% endif %}
        </td>
        <td class="calculated-price">-</td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>
<button id="generateQuotationBtn" class="btn btn-primary mt-3">确认生成报价单</button>
<div id="quotationStatus" class="text-muted small mt-3"></div>
{% else %}
<div class="alert alert-info" role="alert">
  购物车为空，请返回产品列表添加产品。
</div>
{% endif %}
{% endblock %}


{% block scripts %}
<script src="{{ url_for('static', filename='js/decimal.min.js') }}"></script>

<script>
  document.addEventListener('DOMContentLoaded', function () {
    const generateQuotationBtn = document.getElementById('generateQuotationBtn');
    const quotationStatus = document.getElementById('quotationStatus');

    const salespersonSelect = document.getElementById('salesperson');
    const companySelect = document.getElementById('company');
    const currencySelect = document.getElementById('quoteCurrency');
    const profitRateInput = document.getElementById('profitRate');
    const priceHeader = document.getElementById('priceHeader');

    let defaultCurrencyCode = 'USD';

    // 🚀 加载销售员列表
    fetch("/salespersons", {
      method: "POST",
      headers: { "Accept": "application/json" }
    })
      .then(res => res.json())
      .then(salespersons => {
        salespersonSelect.innerHTML = "";
        salespersons.forEach(person => {
          const option = document.createElement("option");
          option.value = person.id;
          option.textContent = person.name;
          salespersonSelect.appendChild(option);
        });
      });

    // 🚀 加载公司列表
    fetch("/companies", {
      method: "POST",
      headers: { "Accept": "application/json" }
    })
      .then(res => res.json())
      .then(companies => {
        companySelect.innerHTML = "";
        companies.forEach(company => {
          const option = document.createElement("option");
          option.value = company.id;
          option.textContent = `${company.name_cn} ${company.name_en}`;
          companySelect.appendChild(option);
        });
      });

    // 🚀 加载货币列表
    fetch("/currencies", {
      method: "POST",
      headers: { "Accept": "application/json" }
    })
      .then(res => res.json())
      .then(currencies => {
        currencySelect.innerHTML = "";
        currencies.forEach(currency => {
          const option = document.createElement("option");
          option.value = currency.code;
          option.textContent = `${currency.code} ${currency.name_cn} ${currency.symbol}`;
          if (currency.code === defaultCurrencyCode) {
            option.selected = true;
          }
          currencySelect.appendChild(option);
        });
        // ⚠️ 等汇率加载完后再计算
        updateExchangeRateDisplay().then(() => {
          updateCalculatedPrices();
        });
      });


    function updateExchangeRateDisplay() {
      const selectedCurrency = currencySelect.value;
      const display = document.getElementById('exchangeRateDisplay');

      return new Promise((resolve) => {
        if (!selectedCurrency || selectedCurrency === 'CNY') {
          display.textContent = '1 CNY = 1 CNY';
          resolve(); // 即刻继续
          return;
        }

        fetch(`/api/exchange_rate/${selectedCurrency}`)
          .then(res => res.json())
          .then(data => {
            if (data.success) {
              display.textContent = `100 ${data.currency} ≈ ${data.rate} CNY（${data.collected_date}）`;
            } else {
              display.textContent = '汇率信息未找到';
            }
            resolve(); // 汇率显示更新完成
          })
          .catch(err => {
            console.error("汇率加载失败", err);
            display.textContent = '汇率加载失败';
            resolve(); // 仍然 resolve，以免卡住
          });
      });
    }


    function updateCalculatedPrices() {
      const Decimal = window.Decimal;

      const profitRate = new Decimal(profitRateInput.value || '0');
      const currencyCode = currencySelect.value || 'USD';
      priceHeader.textContent = `Sales Price (${currencyCode})`;

      let exchangeRate = new Decimal('1.0'); // 默认1:1（CNY时使用）
      if (currencyCode !== 'CNY') {
        // 从汇率显示文本中提取汇率
        const rateText = document.getElementById('exchangeRateDisplay').textContent;
        const rateMatch = rateText.match(/≈ (\d+\.\d+) /);
        if (rateMatch && rateMatch[1]) {
          exchangeRate = new Decimal(rateMatch[1]); // 转换为 1 CNY = x 目标货币
          exchangeRate = exchangeRate.div(100)
        }
      }

      const rows = document.querySelectorAll('tbody tr');
      rows.forEach(row => {
        const costElement = row.querySelector('.data-cost-price');
        const costText = costElement ? costElement.textContent.replace(/[¥￥]/g, '').trim() : '0';
        const cost = new Decimal(costText || '0');
        const priceCell = row.querySelector('.calculated-price');

        if (profitRate.lte(0) || profitRate.gte(100) || cost.lte(0)) {
          priceCell.textContent = '-';
        } else {
          const costWithProfit = cost.div(new Decimal(1).minus(profitRate.div(100)));
          const salePrice = costWithProfit.div(exchangeRate);
          console.log(`成本: ${cost.toString()}, 利润率: ${profitRate.toString()}%, 汇率: ${exchangeRate.toString()}`);
          console.log(`→ 成本加利润: ${costWithProfit.toString()}, 折算售价: ${salePrice.toFixed(2)}`);
          priceCell.textContent = `${salePrice.toFixed(2)} ${currencyCode}`;
        }
      });
    }


    profitRateInput.addEventListener('input', updateCalculatedPrices);
    currencySelect.addEventListener('change', () => {
      updateExchangeRateDisplay().then(() => {
        updateCalculatedPrices(); // 等汇率更新后再计算
      });
    });


    // 💾 提交报价单
    generateQuotationBtn?.addEventListener('click', function () {
      this.disabled = true;
      quotationStatus.textContent = '正在生成报价单...';

      // 🌟 新增：提取购物车商品数据
      const items = [];
      const rows = document.querySelectorAll('tbody tr'); // 获取所有商品行
      rows.forEach(row => {
        // 从行中提取 product_id 和 product_detail_id
        // 注意：需要根据实际HTML结构调整选择器
        const modelCell = row.querySelector('td:nth-child(2)'); // 假设第二列是型号（包含ID信息）
        const costCell = row.querySelector('.data-cost-price'); // 成本价元素

        // 从后端模板渲染的 item 数据中获取 ID（关键！）
        // 由于前端表格是后端用 for循环 渲染的，可在HTML中嵌入数据属性
        // （需要先修改HTML模板，见步骤2）
        const productId = row.dataset.productId;
        const productDetailId = row.dataset.productDetailId;

        // 提取成本价
        const costText = costCell ? costCell.textContent.replace(/[¥￥]/g, '').trim() : '0';
        const costPrice = parseFloat(costText) || 0;

        // 提取计算后的售价（可选，也可由后端重新计算）
        const priceText = row.querySelector('.calculated-price').textContent;
        const unitPrice = parseFloat(priceText) || 0;

        // 添加到 items 列表
        if (productId) {
          items.push({
            product_id: productId,
            product_detail_id: productDetailId || null, // 可能为null
            cost_price: costPrice,
            unit_price: unitPrice,
            // 利润率和利润金额可由后端计算，也可前端传递
            profit_percentage: parseFloat(profitRateInput.value)
          });
        }
      });

      // 🌟 新增：验证商品列表不为空
      if (items.length === 0) {
        quotationStatus.textContent = '请至少选择一个商品';
        this.disabled = false;
        return;
      }

      // 构建请求数据（包含 items）
      const requestData = {
        quote_currency: currencySelect.value,
        profit_rate: parseFloat(profitRateInput.value),
        salesperson: salespersonSelect.value,
        company_id: companySelect.value,
        items: items // 🌟 关键：添加 items 字段
      };

      // 发送请求（保持不变）
      fetch('/create_quotation', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(requestData)
      })
        .then(res => res.json())
        .then(data => {
          // 处理响应（保持不变）
          if (data.success) {
            quotationStatus.innerHTML = `✅ 报价单生成成功！编号：${data.quotation_number} <a href="${data.quotation_url}" class="btn btn-sm btn-outline-primary ms-2">查看报价单</a>`;
            generateQuotationBtn.style.display = 'none';
          } else {
            quotationStatus.textContent = `❌ ${data.message}`;
            generateQuotationBtn.disabled = false;
          }
        })
        .catch(err => {
          console.error(err);
          quotationStatus.textContent = '生成失败，请检查控制台或后端日志';
          generateQuotationBtn.disabled = false;
        });
    });
  });
</script>

{% endblock %}